<template>
    <Category :scene="1"></Category>

    <el-card style="margin:10px 0">
        <el-button type="primary" icon="Plus" size="default" style="float: right; margin-bottom: 15px"
            @click="AddBrand">添加品牌</el-button>

        <el-table border :data="brandShowList" height="560">
            <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
            <el-table-column label="品牌名称" align="center" prop="tmName"></el-table-column>
            <el-table-column label="品牌LOGO" align="center">
                <template #="{ row, $index }">
                    <img :src="row.logoUrl" alt="" style="width: 30%;">
                </template>
            </el-table-column>
            <el-table-column label="品牌操作" align="center">
                <template #="{ row, $index }">
                    <el-button icon="Edit" type="primary" size="small" @click="upBrand(row)"></el-button>
                    <el-popconfirm title="您是否确定删除该条数据？" width="215px" icon="delete" @confirm="RemoveBrand(row.id)">
                        <template #reference>
                            <el-button icon="Delete" type="danger" size="small"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination style="margin-top: 15px;" v-model:current-page="PageNo" v-model:page-size="PageLimit"
            :page-sizes="[10, 20, 40]" :pager-count="3" :disabled="disabled" :background="background"
            layout="prev, pager, next, jumper,->, sizes, total" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </el-card>

    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="BrandForm.id ? '修改品牌' : '添加品牌'" width="700">
        <el-form :model="BrandForm" style="width: 75%;" :rules="rules" ref="formRef">
            <el-form-item label="品牌名称" prop="tmName">
                <el-input v-model="BrandForm.tmName" autocomplete="off" />
            </el-form-item>

            <el-form-item label="品牌图片" prop="logoUrl">
                <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="BrandForm.logoUrl" :src="BrandForm.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { ref, reactive, onMounted, nextTick } from 'vue'
    import { ElMessage } from 'element-plus'
    import { reqBrand, reqAddUpdataBrand, reqDeleteBrand } from '@/api/product/brand'
    import { Records, BrandResponseData, Brand } from '@/api/product/brand/type'
    import type { UploadProps } from 'element-plus'

    const PageNo = ref<number>(1)
    const PageLimit = ref<number>(10)
    const background = ref<boolean>(true)
    const disabled = ref<boolean>(false)

    const brandShowList = ref<[]>([])
    const total = ref<number>(0)

    const dialogFormVisible = ref<boolean>(false)
    const BrandForm = reactive<Brand>({
        tmName: '',
        logoUrl: '',
    })
    const formRef = ref()

    // 获取品牌数据
    const getHasBrand = async (pager = 1) => {
        PageNo.value = pager
        let res: any = await reqBrand(PageNo.value, PageLimit.value)
        if (res.code === 200) {
            console.log('--------------------------获取品牌数据成功--------------------------')
            brandShowList.value = res.data.records
            total.value = res.data.total
        }
    }

    // 改：每页val条
    const handleSizeChange = () => {
        // 当前每一页的数据量发生变化的时候，当前页码归1
        getHasBrand()
    }

    // 翻页
    const handleCurrentChange = (val: number) => {
        getHasBrand(val)
    }

    // 上传图片:成功
    const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
        BrandForm.logoUrl = response.data;
        formRef.value.clearValidate('logoUrl')
        ElMessage({
            type: 'success',
            message: '图片上传成功！'
        });
    }

    // 上传图片:上传之前触发的钩子函数
    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
        if (rawFile.type == 'image/png' ||
            rawFile.type == 'image/jpeg' &&
            rawFile.size / 1024 / 1024 < 4
        ) {
            return true
        } else {
            ElMessage({
                type: 'error',
                message: '图片不符合要求！'
            })
            return false
        }
    }

    // 添加品牌
    const AddBrand = () => {
        dialogFormVisible.value = true;
        Object.assign(BrandForm, { logoUrl: '', tmName: '', id: null })
        formRef.value?.clearValidate('tmName');
        formRef.value?.clearValidate('logoUrl');
    }

    // 确认：添加品牌 && 修改品牌
    const confirm = async () => {
        await formRef.value.validate()
        let res: any = await reqAddUpdataBrand(BrandForm);
        // 成功
        console.log(res)
        if (res.code == 200) {
            dialogFormVisible.value = false;
            ElMessage({
                type: 'success',
                message: BrandForm.id ? '修改品牌成功！' : '添加品牌成功！'
            });
            getHasBrand(brandShowList.value.length >= 5 ? PageNo.value + 1 : PageNo.value);
        } else {
            ElMessage({
                type: 'error',
                message: BrandForm.id ? '修改品牌失败！' : '添加品牌失败！'
            });
            dialogFormVisible.value = false;
        }
    }

    // 取消
    const cancel = () => {
        dialogFormVisible.value = false;
    }

    // 修改品牌
    const upBrand = (row: Brand) => {
        dialogFormVisible.value = true;
        Object.assign(BrandForm, row)
        nextTick(() => {
            formRef.value.clearValidate('tmName');
            formRef.value.clearValidate('logoUrl');
        })
    }

    // 删除品牌
    const RemoveBrand = async (id: number) => {
        console.log(`删除id为 ${id} 的品牌`)
        let res = await reqDeleteBrand(id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除品牌成功!'
            })
            getHasBrand(brandShowList.value.length > 1 ? PageNo.value : PageNo.value - 1,)
        } else {
            ElMessage(
                {
                    type: 'error',
                    message: '删除品牌失败!'
                })
        }
    }


    // 自定义校验规则-NAME
    const validatorTmName = (rule: any, value: any, callBack: any) => {
        if (value.trim().length >= 2) {
            callBack()
        } else {
            callBack(new Error('品牌名称位数大于等于两位'))
        }
    }

    // 自定义校验规则-LOGO
    const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
        if (value) {
            callBack()
        } else {
            callBack(new Error('Logo的图片务必上传'))
        }
    }

    // 自定义规则
    const rules = {
        tmName: [
            {
                required: true,
                trigger: 'blur',
                validator: validatorTmName,
            },
        ],
        logoUrl: [
            {
                required: true,
                trigger: 'change',
                validator: validatorLogoUrl,
            },
        ],
    }

    // 挂载完毕
    onMounted(() => {
        console.log('------------------------------初始化-------------------------------')
        getHasBrand()
    })
</script>
<script lang="ts">
    export default {
        name: 'Brand'
    }
</script>

<style lang="scss" scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>